<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100" type="textarea"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								:auth="true"
								:rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" label="所属部门" :org-id="stateData.vmModel.Entity.OrgId" :auth="true" />
						</el-col>
					</el-row>
				</div>

				<div class="form-section" v-if="stateData.vmModel.Entity.ID">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>岗位分配明细</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<SysHrJobAssignmentRequestBillEntry
								:search-bar="false"
								:toolbar="true"
								:is-disabled="true"
								:entity-id="stateData.vmModel.Entity.ID"
								:group-id="stateData.vmModel.Entity.GroupId"
								:org-id="stateData.vmModel.Entity.OrgId"
							/>
						</el-col>
					</el-row>
				</div>

				<!-- 当主表未保存时的提示 -->
				<div class="form-section" v-else-if="!loading">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-tips"></i>
						<span>提示</span>
					</div>
					<el-alert title="请先保存主表信息" description="保存主表后，才能添加岗位分配明细信息" type="info" :closable="false" show-icon />
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import { ElMessage } from 'element-plus';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, defineAsyncComponent, type ComponentInternalInstance } from 'vue';
import { SysHrJobAssignmentRequestBillApi as api } from '/@/views/hr/syshrjobassignmentrequestbill/api';
import other from '/@/utils/other';
import { ISysHrJobAssignmentRequestBillVm } from '/@/views/hr/syshrjobassignmentrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';
import { getCurrentUserMainGroupId } from '/@/utils/userGroup';

// 懒加载子组件
const SysHrJobAssignmentRequestBillEntry = defineAsyncComponent(() => import('/@/views/hr/syshrjobassignmentrequestbillentry/index.vue'));

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 获取用户信息store
const userInfoStore = useUserInfo();

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrJobAssignmentRequestBillVm>>({
	vmModel: {
		Entity: {
			Approver: null,
			ApprovalTime: null,
			ApprovalOpinion: null,
			GroupId: null,
			OrgId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [],
});

// 计算属性
const hasEntityId = computed(() => !!stateData.vmModel.Entity.ID);

// 统一的API响应处理函数
const handleApiResponse = (response: any, isSubmit = false) => {
	const messageKey = isSubmit ? 'message._system.common.vm.submittip' : 'message._system.common.vm.savetip';
	ElMessage.success(ci.proxy?.$t(messageKey) || (isSubmit ? '提交成功' : '保存成功'));
	emit('refresh');

	// 统一处理ID设置 - 确保主表ID正确设置以便传递给子表
	if (response?.Entity?.ID) {
		// 完整实体返回，更新整个Entity
		stateData.vmModel.Entity = response.Entity;
		console.log('主表保存成功，获取到主表ID:', response.Entity.ID);
	} else if (response?.ID) {
		// 只返回ID，仅更新ID字段
		stateData.vmModel.Entity.ID = response.ID;
		console.log('主表保存成功，获取到主表ID:', response.ID);
	} else if (response?.Data?.ID) {
		// API返回Data包装格式
		stateData.vmModel.Entity.ID = response.Data.ID;
		console.log('主表保存成功，获取到主表ID:', response.Data.ID);
	} else {
		console.warn('主表保存成功但未获取到ID，无法关联子表', response);
	}

	if (isSubmit) {
		closeDialog();
	} else {
		hasSavedOnce.value = true;
	}

	loading.value = false; // 重置loading状态

	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	console.error('主表操作失败:', error);

	// 如果是保存失败，确保不影响后续的保存操作
	if (error?.message?.includes('保存') || error?.message?.includes('add')) {
		ElMessage.error('主表保存失败，请检查必填字段后重试');
		hasSavedOnce.value = false; // 重置保存状态，允许重新保存
	} else {
		ElMessage.error('操作失败，请重试');
	}

	other.setFormError(ci, error);
	loading.value = false;

	// 确保按钮状态正确
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 公共的表单提交函数
const submitForm = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	submitForm(
		() => api().add(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false
	);
};

// 提交
const onSubmit = () => {
	submitForm(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [billCode] = await Promise.allSettled([api().getBillCode()]);

	// 处理成功的结果
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value?.Data || null;

	// 设置默认部门为当前用户的主要部门
	if (!stateData.vmModel.Entity.GroupId) {
		stateData.vmModel.Entity.GroupId = getCurrentUserMainGroupId();
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 确保用户信息已加载
		await userInfoStore.setUserInfos();
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: hasEntityId.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
